//
//  SafariObserver.m
//  Do Not Disturb
//
//  Created by Chris Karr on 9/17/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "WebBrowserObserver.h"
#import "DNDDefines.h"

@implementation WebBrowserObserver

- (NSString *) getName
{
	return @"Web Browser";
}

- (void) scan
{
	BOOL safariOpen = NO;
	BOOL firefoxOpen = NO;
	
	NSWorkspace * workspace = [NSWorkspace sharedWorkspace];

	NSDictionary * active = [workspace activeApplication];

	if ([[active valueForKey:@"NSApplicationName"] isEqual:@"Safari"])
		safariOpen = YES;
	else if ([[active valueForKey:@"NSApplicationName"] isEqual:@"Firefox"])
		firefoxOpen = YES;

	NSArray * apps = [workspace launchedApplications];
	
	int i = 0;
	for (i = 0; i < [apps count]; i++)
	{
		if ([[[apps objectAtIndex:i] valueForKey:@"NSApplicationName"] isEqual:@"Safari"])
			safariOpen = YES;
		else if ([[[apps objectAtIndex:i] valueForKey:@"NSApplicationName"] isEqual:@"Firefox"])
			firefoxOpen = YES;
	}

	if (safariOpen)
	{
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\"\n\
																			if (exists document 1) then\n\
																				URL of document 1\n\
																			end if\n\
																		end tell"];

		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil && [desc stringValue] != nil)
		{
			NSURL * url = [NSURL URLWithString:[desc stringValue]];
			
			NSString * host = [url host];
			
			if (host == nil)
				host = @"localhost";
				
			NSMutableDictionary * dict = [NSMutableDictionary dictionary];
			[dict setValue:[NSDate date] forKey:@"date"];
			[dict setValue:[NSString stringWithFormat:@"Current Safari URL host: %@", host] forKey:@"name"];
	
			[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"SafariObserver" userInfo:dict];		
		}
	}

	if (firefoxOpen)
	{
		NSAppleScript * script = [[NSAppleScript alloc] initWithSource:@"tell application \"Firefox\"\n\
																			set myFirefox to properties of front window as list\n\
																			get item 3 of myFirefox\n\
																		end tell"];

		NSAppleEventDescriptor * desc = [script executeAndReturnError:nil];
		
		if (desc != nil && [desc stringValue] != nil)
		{
			NSURL * url = [NSURL URLWithString:[desc stringValue]];
			
			NSString * host = [url host];
			
			if (host == nil)
				host = @"localhost";
				
			NSMutableDictionary * dict = [NSMutableDictionary dictionary];
			[dict setValue:[NSDate date] forKey:@"date"];
			[dict setValue:[NSString stringWithFormat:@"Current Firefox URL host: %@", host] forKey:@"name"];
	
			[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"SafariObserver" userInfo:dict];		
		}
	}
}

@end
